package cn.kgc.springday05.proxys;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;

import java.lang.reflect.Method;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/6/16
 * @Description:  基于父子类的代理方式
 */
public class CglibProxy {

    private Object target;

    public CglibProxy(Object object){
        this.target = object;
    }

    public  Object  getProxy(){
        Enhancer enhancer = new Enhancer();
        //设置代理对象的父类
        enhancer.setSuperclass(target.getClass());
        //编写增强业务的对象
        InvocationHandler invocationHandler = new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {

                System.out.println("===========上课时间到了================");
                // 被代理对象方法的执行
                Object invoke = method.invoke(target, objects);

                return invoke;
            }
        };
        enhancer.setCallback(invocationHandler);

        Object o = enhancer.create();
        return o;
    }

}
